#!/usr/bin/perl -w

# this script populate total tcp traffic log file to display it by http.

BEGIN   
{
    sub getPoints{return '../../' if (!$_[1]);return '../' if (!$_[0]);return '/';}
    (my $file = __FILE__) =~ s/(\/?modules)?(\/?tcp_logging)?\/?\w+\.pl$/&getPoints($1,$2)/e;
    $file = './' if $file eq '/';
    unshift(@INC, $file."bin");
    unshift(@INC, $file."modules/tcp_logging");
}

use strict;
use TWM;
use Data::Dumper;
use TrafficLogging;

my ($local_iface, $gw) = ('')x2;
my $isp_list = &getISP;
for (keys %$isp_list)
{
	$local_iface = $isp_list->{$_}->{inf} if $isp_list->{$_}->{attributes}->{internal};
	$gw = $isp_list->{$_}->{inf} if $isp_list->{$_}->{attributes}->{default};
}
$ck{debug_level}>4 && toDebugLog("Default gateway is $gw. Local interface is $local_iface.");
my $is_changed = 0;

my $trafficLogging = TrafficLogging->new();
my $report_file = "$ck{twmfolder}modules/$mc/logs/".$trafficLogging->get_report_filename();
$ck{debug_level}>4 && toDebugLog("Report file name is $report_file");

my $xmlip = readConfigFile($ck{scfolder}.$ck{_ip_list});
my $ip_items = $xmlip->{items}->{item};
my $blocked = readModuleConfigFile($cm{tcp_blocked});
$blocked->{pc} = [$blocked->{pc}] if ref $blocked->{pc} eq 'HASH';
if (! -e $report_file)
{
	if ($cm{enable_blocked})
	{
		for (my $j=0; $j<=$#{$blocked->{pc}}; $j++)
		{
			for (my $i=0; $i<=$#{$ip_items}; $i++)
			{
				if ($ip_items->[$i]->{ip} eq $blocked->{pc}[$j]->{ip} && !$ip_items->[$i]->{enabled})
				{
					$ip_items->[$i]->{enabled} = 1;
					$is_changed = 1;
				}
			}
		}
	}
	$blocked->{pc} = [];
	system "echo > $report_file; chmod 666 $report_file;";
}

my @res = run_twm_script($cm{ipt_traffic_script}, $mc);
for (@res)
{
	if (/(\d+)\t(\-?\-?\>?\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\-?\-?\>?)\t(.+?)\t(.+)/)
	{
		my ($ip, $size, $if, $rule) = ($2, $1, $3, $4);
		if ($size && $rule =~ /mangle_MARK_PREROUTING/)
		{
# here is problem with traffic calculation if user uses second ISP with http partly
			$trafficLogging->{repArray}->[1]->{$ip."\t".$gw} -= $size;
			$trafficLogging->{repArray}->[1]->{$ip."\t".$gw} = 0 if ($trafficLogging->{repArray}->[1]->{$ip."\t".$gw} < 0);
			$trafficLogging->{repArray}->[0]->{$ip."\t".$gw} -= $size;
			$trafficLogging->{repArray}->[0]->{$ip."\t".$gw} = 0 if ($trafficLogging->{repArray}->[0]->{$ip."\t".$gw} < 0);
		}
		$trafficLogging->{repArray}->[1]->{$ip."\t".$if} += $size;
		$trafficLogging->{repArray}->[0]->{$ip."\t".$if} += $size;
	}
}

open(REPORTS, "+<$report_file") || (toErrorLog("Can't open $report_file: $!") && die("Can't open $report_file: $!\n"));
my $index;
REP: while (<REPORTS>)
{
	chomp;
	next REP if (!$_ || $_ =~ /^#/);
	$trafficLogging->populate_report_item($_);
}
print Dumper $trafficLogging->{repArray}->[0];
seek(REPORTS,0,0) || die "Seeking: $!\n";
#my @showM = split /\,/, $cm{log_items_list};
my @showM = @{$trafficLogging->get_items_list()};
my $max_history = pop @showM;
for (my $i=0; $i<=$max_history; $i++)
{
	print REPORTS "=${i}M\n";
	print REPORTS "\t$_\t".$trafficLogging->{repArray}->[$i+1]->{$_}."\n" foreach (sort keys %{$trafficLogging->{repArray}->[$i+1]});
	print REPORTS "\n";
}
print REPORTS "=TotalM\n";
print REPORTS "\t$_\t".$trafficLogging->{repArray}->[0]->{$_}."\n" foreach (sort keys %{$trafficLogging->{repArray}->[0]});
print REPORTS "\n";

truncate(REPORTS, tell(REPORTS)) || (toErrorLog("Truncating: $!") && die "Truncating: $!\n");
close(REPORTS) || die "Close: $!\n";

########################################
#	TCP restriction
########################################
my ($limits, $str) = (undef, '');

my $xml = &readModuleConfigFile($cm{tcp_limit});
$xml->{'pc'} = [$xml->{'pc'}] if ref $xml->{'pc'} eq 'HASH';
$limits->{$_->{ip}} = $_->{size}*1024**2 for (@{$xml->{'pc'}});

my $default_size = $cm{default_size}*1024**2;
my $ip_name = get_ip_name_hash(&getIPs);
my $total_traffic = $trafficLogging->total_traffic();
my @new_blocked;
foreach (keys %$total_traffic)
{
	my $limit = exists($limits->{$_})?$limits->{$_}:$default_size;
	my $total = $total_traffic->{$_};
	if ($total >= $limit)
	{
		for (my $i=0; $i<=$#{$ip_items}; $i++)
		{
			if ($ip_items->[$i]->{ip} eq $_ && $ip_items->[$i]->{enabled})
			{
				push @{$blocked->{pc}}, {'ip'=>$_};
				push @new_blocked, $_;
				$ip_items->[$i]->{enabled} = 0;
				$is_changed = 1;
				my $name = exists($ip_name->{$_})?$ip_name->{$_}:"Unknown";
				$str .= "Disabled $name ($_) tcp traffic.\nTotal: ${\(getHumanTrafficNumber($total, 'm'))} Mb.\nLimit: ${\(getHumanTrafficNumber($limit, 'm'))} Mb.\n";
			}
		}
	}
}

if ($is_changed)
{
	if ($str)
	{
		toDebugLog($str);
		send_email(
			{
				'to' => $cm{email_to},
				'subject' => $cm{email_subject},
				'body' => "Hi All,\n\n$str\n\nBest.\nRobot."
			}
		);
	}
	saveModuleConfigFile($cm{tcp_blocked}, $blocked);
	enableIPs(\@new_blocked,0);
}

__END__

